
package com.shop.cloud.mall.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.mall.common.entity.*;
import com.shop.cloud.mall.api.mapper.OrderRefundsMapper;
import com.shop.cloud.mall.common.enums.OrderItemEnum;
import com.shop.cloud.mall.api.service.OrderItemService;
import com.shop.cloud.mall.api.service.OrderRefundsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 退款详情
 *
 * @author
 * @date 2019-11-14 16:35:25
 */
@Slf4j
@Service
@AllArgsConstructor
public class OrderRefundsServiceImpl extends ServiceImpl<OrderRefundsMapper, OrderRefunds> implements OrderRefundsService {

	private final OrderItemService orderItemService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	@Klock(name = "SaveOrderRefunds", keys = {"#entity.getOrderItemId()"}, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
	public boolean saveRefunds(OrderRefunds entity) {
		OrderItem orderItem = orderItemService.getById(entity.getOrderItemId());
		if(StrUtil.isNotBlank(entity.getStatus())
				&& orderItem != null
				&& CommonConstants.NO.equals(orderItem.getIsRefund())
		 		&& (OrderItemEnum.STATUS_0.getValue().equals(orderItem.getStatus())
						|| OrderItemEnum.STATUS_12.getValue().equals(orderItem.getStatus())
						|| OrderItemEnum.STATUS_22.getValue().equals(orderItem.getStatus())
						|| OrderItemEnum.STATUS_212.getValue().equals(orderItem.getStatus()))
					){//只有未退款的订单才能发起退款
			//修改订单详情状态为退款中
			orderItem.setStatus(entity.getStatus());
			orderItem.setIsRefund(CommonConstants.NO);
			orderItemService.updateById(orderItem);
			//新增退款记录
			entity.setShopId(orderItem.getShopId());
			entity.setOrderId(orderItem.getOrderId());
			entity.setOrderItemId(orderItem.getId());
			entity.setRefundAmount(orderItem.getPaymentPrice());
			entity.setSupplierId(orderItem.getSupplierId());
			baseMapper.insert(entity);
		}
		return Boolean.TRUE;
	}

}
